<template>
	<view>
		<view style="height: calc(100vh - 240px);display: flex;align-items: center;">
			<view style="position: relative;">
				<canvas
					:style="`width: ${canvasStyle.w}px; height: ${canvasStyle.h}px;position: absolute;top: 0;left: 0;z-index:10`"
					id="myCanvas" canvas-id="myCanvas" :disable-scroll="true" @touchstart.stop="penStart"
					@touchmove.stop="penMove" @touchend.stop="penEnd">
				</canvas>
				<canvas :style="`width: ${canvasStyle.w}px; height: ${canvasStyle.h}px;`" id="myCanvasImg"
					canvas-id="myCanvasImg" :disable-scroll="true">
				</canvas>
			</view>
		</view>
		<view class="" style="position: fixed;bottom: 0;left: 0;width: 100%;background: #fff;">
			<view style="height: 60px;margin-bottom: 10px;">
				<view class="" style="display: flex;height: 60px;align-items: center;justify-content: space-around;"
					v-if="shapeFlag">
					<view v-for="(item, idx) in shapes" :key="idx" @click="shape=item.shape">
						<u-icon v-if="item.shape==='curve'" name="edit-pen-fill" :color="shape==='curve'? '#0081FF': ''"
							size="27"></u-icon>
						<!-- 横线 -->
						<u-icon v-if="item.shape==='line'" name="minus" :color="shape==='line'? '#0081FF': ''"
							size="27"></u-icon>
						<!-- 矩形 -->
						<image v-if="item.shape==='hollow-rect' &&  shape==='hollow-rect'"
							src="../../static/editImage/juxing-on.png" mode="" style="width: 48rpx;height:48rpx;">
						</image>
						<image v-if="item.shape==='hollow-rect' && shape!=='hollow-rect'"
							src="../../static/editImage/juxing-off.png" mode="" style="width: 48rpx;height:48rpx;">
						</image>
						<!-- 圆形空心 -->
						<uni-icons v-if="item.shape==='hollow-circle'" type="circle" size="27"
							:color="shape==='hollow-circle'?  '#0081FF': ''"></uni-icons>
					</view>
				</view>
				<view class=" " style="padding: 0 10rpx;height: 60px;margin-bottom: ;" v-if="colorFlag">
					<view class="lxy-content">
						<scroll-view scroll-x="true" class="content-scroll" scroll-with-animation :scroll-left="0">
							<view v-for="(item, idx) in colors" :key="idx" class="scroll-item"
								:style="`width:100rpx;height:90rpx;margin-bottom: 20rpx;margin-right: 20rpx;background-color: ${item.color};`"
								:class="color==item.color?'active':''" @click="color=item.color">
								<!-- {{item.name}} -->
							</view>
						</scroll-view>
					</view>
				</view>
				<view class="flex-row align-center justify-around mglr-50 pdb-5" style="height: 60px;" v-if="sizeFlag">
					<view v-for="(item, idx) in sizes" :key="idx" class="square-20p flex-row flex-center"
						@click="lineWidth=item.lineWidth">
						<view class="round" :class="lineWidth==item.lineWidth?'activeSize':''"
							:style="`width:${item.lineWidth}px;height:${item.lineWidth}px;background:${lineWidth==item.lineWidth?'#0081FF':'#ccc'}`">
						</view>
					</view>
				</view>
			</view>
			<view style="height: 60px;margin-bottom: 10px;">
				<view style="display: flex;justify-content: space-around;align-items: center;">
					<view @click="shapeFlag = true,
					colorFlag = false,
					sizeFlag = false">
						<view
							style="width: 27px;height: 27px;display: flex;align-items: center;justify-content: center;overflow: hidden;">
							<u-icon name="edit-pen-fill" size="27" :color="`${shapeFlag?'#0081FF':'#000'}`"></u-icon>
						</view>
						<p :style="`color:${shapeFlag?'#0081FF':'#000'}`">涂鸦</p>
					</view>
					<view @click="shapeFlag = false,
					colorFlag = true,
					sizeFlag = false">
						<view
							style="width: 27px;height: 27px;display: flex;align-items: center;justify-content: center;overflow: hidden;">
							<uni-icons type="circle-filled" size="27"
								:style="`color:${colorFlag?'#0081FF':'#000'}`"></uni-icons>
						</view>
						<p :style="`color:${colorFlag?'#0081FF':'#000'}`">颜色</p>
					</view>
					<view @click="shapeFlag = false,
					colorFlag = false,
					sizeFlag = true">
						<view
							style="width: 27px;height: 27px;overflow: hidden;display: flex;align-items: center;justify-content: center;">
							<uni-icons type="smallcircle" size="27"
								:style="`color:${sizeFlag?'#0081FF':'#000'}`"></uni-icons>
						</view>
						<p :style="`color:${sizeFlag?'#0081FF':'#000'}`">粗细</p>
					</view>
					<view @click="repeal">
						<view
							style="width: 27px;height: 27px;display: flex;align-items: center;justify-content: center;overflow: hidden;">
							<image src="../../static/editImage/chexiao-off.png" mode=""
								style="width: 27px;height: 27px;display: inline-block;" v-if="curStep<=0">
							</image>
							<image src="../../static/editImage/chexiao-on.png" mode=""
								style="width: 27px;height: 27px;display: inline-block;" v-if="curStep>0"></image>
						</view>
						<p :style="`color:${curStep>0?'#000':'#ccc'}`">撤销</p>
					</view>
					<view @click="redo">
						<view
							style="width: 27px;height: 27px;display: flex;align-items: center;justify-content: center;overflow: hidden;">
							<image src="../../static/editImage/chongzuo-off.png" mode=""
								style="width: 27px;height: 27px;display: inline-block;"
								v-if="curStep===imageData.length-1">
							</image>
							<image src="../../static/editImage/chongzuo-on.png" mode=""
								style="width: 27px;height: 27px;display: inline-block;"
								v-if="curStep<imageData.length-1">
							</image>
						</view>
						<p :style="`color:${curStep===imageData.length-1?'#ccc':'#000'}`">重做</p>
					</view>
					<view @click="clearBoard">
						<view
							style="width: 27px;height: 27px;display: flex;align-items: center;justify-content: center;overflow: hidden;">
							<yl-icon icon="custom-icon-clear" :size="'size-22'" :color="curStep>0?'#000':'#ccc'"
								style="width: 27px;height: 27px;display: inline-block;color:#ccc"></yl-icon>
						</view>
						<p :style="`color:${curStep>0?'#000':'#ccc'}`">清空</p>
					</view>
					<!-- <yl-icon icon="text-gray" size="size-22" color="text-blue"></yl-icon> -->
					<!-- text-black  text-blue-->

					<!-- <yl-icon icon="custom-icon-clear" :size="'size-22'" color="text-blue"></yl-icon> -->


				</view>
			</view>
			<view class="" style="height: 50px;display: flex;justify-content: space-between;padding: 10px 20px;">
				<uni-icons type="closeempty" size="30" color="'#523339'" style="height: 30px;"
					@click="navBack"></uni-icons>
				<uni-icons type="checkmarkempty" size="30" color="'#523339'" style="height: 30px;"
					@click="savePicture"></uni-icons>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				type: "",
				index: "",
				picture: "",
				canvasStyle: {},
				ctx: null,
				myCanvasImg: null,
				startX: '', //开始路径点X
				startY: '', //开始路径点Y
				isDrawing: false,
				imageData: [], //步骤列表
				curStep: 0, //当前步
				color: '#ff0000',
				lineWidth: 3,
				shape: "curve", //画笔形状
				shapeFlag: true,
				shapes: [{
						icon: "cuicon-write", //画笔
						shape: "curve",
						active: true
					},
					{
						icon: "cuicon-move",
						shape: "line",
						active: false
					},

					{
						icon: "cuicon-square",
						shape: "hollow-rect",
						active: false
					},

					{
						icon: "cuicon-round",
						shape: "hollow-circle",
						active: false
					}
				],
				colorFlag: false,
				colors: [ //画笔颜色
					{
						color: "#ff0000",
						active: true
					},
					{
						color: "#1c9d02",
						active: false
					},
					{
						color: "#000000",
						active: false
					},
					{
						color: "#006ce6",
						active: false
					},
					{
						color: "#efaa03",
						active: false
					},
					{
						color: "#FFFF00",
						active: false
					},
					{
						color: "#00FFFF",
						active: false
					},
					{
						color: "#FF00FF",
						active: false
					},
					{
						color: "#00FF01",
						active: false
					},

				],
				sizeFlag: false,
				sizes: [ //画笔粗细
					{
						lineWidth: 3,
						active: true
					},
					{
						lineWidth: 6,
						active: false
					},
					{
						lineWidth: 9,
						active: false
					},
					{
						lineWidth: 12,
						active: false
					},

					{
						lineWidth: 15,
						active: false
					},

				],
			}
		},
		onLoad(query) {
			this.type = query.type
			this.index = query.index
			this.picture = query.picture
			this.canvasStyle = query.style ? JSON.parse(query.style) : {}

		},
		mounted() {
			this.$nextTick(() => {
				this.Init()
			})
		},
		watch: {
			shape(val) {
				if (val === 'curve') {

				} else if (val === 'line') {

				} else if (val === 'hollow-rect') {

				} else if (val === 'hollow-circle') {

				}
			}
		},
		methods: {
			navBack() {
				uni.navigateBack()
			},
			savePicture() {
				if (this.curStep === 0) {
					this.navBack()
					return
				}
				uni.showLoading({
					title: '涂鸦保存中',
					mask: true,
				})
				let res = this.imageData[this.curStep]
				console.log(res);
				// uni.showLoading({
				// 	mask: true
				// });

				// this.picture = res;

				var imglist = []
				var obj = {}
				var newImgList = []
				if (this.type == 'local') imglist = JSON.parse(uni.getStorageSync('localImgList'))
				else if (this.type == 'upload') {
					obj = JSON.parse(uni.getStorageSync('uploadImgList'))
					imglist = obj.content
				} else {
					this.type == 'edit'
					obj = JSON.parse(uni.getStorageSync('editImgList'))
					imglist = obj.content
				}
				console.log(uni.getStorageSync('localImgList'));
				console.log(uni.getStorageSync('uploadImgList'));
				console.log(uni.getStorageSync('editImgList'));

				// console.log('是否执行到这里了',obj,imglist, this.type, this.index, this.oldPicture, this.picture, this.$store.state.ImageList)

				uni.saveFile({
					tempFilePath: res,
					success: (val) => {
						if (this.type == 'edit') {
							newImgList = JSON.parse(uni.getStorageSync('editImgList'))
								.content
							newImgList[this.index].Murl = val.savedFilePath
						} else {
							if (imglist.length > 1) {
								imglist[this.index].Murl = val.savedFilePath
							} else {
								imglist[0].Murl = val.savedFilePath
							}
						}

						if (this.type == 'local') {
							uni.setStorageSync(
								'localImgList', JSON.stringify(imglist))
							// console.log('匹配到这里处理local', obj, imglist)
						} else if (this.type == 'upload') {
							obj.content = imglist
							uni.setStorageSync('uploadImgList', JSON
								.stringify(obj))
							let formArr = JSON.parse(uni.getStorageSync('fromdata'))
							formArr[obj.vix].imglist = imglist
							uni.setStorageSync('fromdata', JSON.stringify(
								formArr))
							// console.log('匹配到这里处理upload', obj, imglist)
						} else {
							// obj.content = imglist
							let newObj = {
								Murl: newImgList[this.index].Murl,
								name: newImgList[this.index].name,
								index: this.index
							}
							this.$store.commit('setImageList', newObj)
						}
						uni.hideLoading()
						// 返回上一页
						uni.navigateBack()
					},
					complete: () => {
						uni.hideLoading()
					}
				});
			},
			resetImg() {
				console.log(this.curStep);
				this.myCanvasImg.drawImage(this.imageData[this.curStep], 0, 0, this.canvasStyle.w, this.canvasStyle.h);
				this.myCanvasImg.draw(false);
				this.ctx.draw(false);
			},
			//清空
			clearBoard() {
				if (this.curStep == 0) {
					return
				}
				this.imageData = [this.picture]
				this.curStep = 0
				this.resetImg()
			},
			//重做上一步
			redo() {
				if (this.curStep === this.imageData.length - 1) {
					return
				}
				this.curStep++
				this.resetImg()
			},
			//撤销
			repeal() {
				console.log(this.curStep);
				console.log(this.imageData);
				if (this.curStep === 0) {
					return
				}
				this.curStep--
				this.resetImg()
			},
			//圆形
			drawCircle(x, y, isImg) {
				let pointLT = {};
				let pointRB = {};
				let center = {};

				pointLT.X = Math.min(this.startX, x);
				pointLT.Y = Math.min(this.startY, y);

				pointRB.X = Math.max(this.startX, x);
				pointRB.Y = Math.max(this.startY, y);

				center.X = (pointRB.X + pointLT.X) / 2;
				center.Y = (pointRB.Y + pointLT.Y) / 2;

				let dx = pointRB.X - pointLT.X;
				let dy = pointRB.Y - pointLT.Y;
				let r = Math.sqrt(dx * dx + dy * dy) / 2;

				// this.ctx.beginPath();
				// this.ctx.arc(center.X, center.Y, r, 0, 2 * Math.PI);
				// this.ctx.stroke();
				// this.ctx.draw();

				if (isImg) {
					this.myCanvasImg.beginPath();
					this.myCanvasImg.setStrokeStyle(this.color); // 设置线条颜色
					this.myCanvasImg.setLineWidth(this.lineWidth); // 设置线条宽度  
					this.myCanvasImg.arc(center.X, center.Y, r, 0, 2 * Math.PI);
					this.myCanvasImg.stroke();
					this.myCanvasImg.draw(true);
				} else {
					this.ctx.beginPath();
					this.ctx.setStrokeStyle(this.color); // 设置线条颜色  
					this.ctx.setLineWidth(this.lineWidth); // 设置线条宽度  
					this.ctx.arc(center.X, center.Y, r, 0, 2 * Math.PI);
					this.ctx.stroke();
					this.ctx.draw(false);
				}

			},
			//方形
			drawRect(x, y, isImg) {
				let pointLT = {};
				let pointRB = {};
				let pointRT = {};
				let pointLB = {};
				let center = {};

				pointLT.X = Math.min(this.startX, x);
				pointLT.Y = Math.min(this.startY, y);

				pointRB.X = Math.max(this.startX, x);
				pointRB.Y = Math.max(this.startY, y);

				pointRT.X = pointRB.X;
				pointRT.Y = pointLT.Y;

				pointLB.X = pointLT.X;
				pointLB.Y = pointRB.Y;

				let width = Math.abs(x - this.startX);
				let height = Math.abs(y - this.startY);

				if (isImg) {
					this.myCanvasImg.beginPath();
					this.myCanvasImg.setStrokeStyle(this.color); // 设置线条颜色
					this.myCanvasImg.setLineWidth(this.lineWidth); // 设置线条宽度  
					this.myCanvasImg.rect(pointLT.X, pointLT.Y, width, height);
					this.myCanvasImg.stroke(); // 只绘制边框  
					this.myCanvasImg.draw(true);
				} else {
					this.ctx.beginPath();
					this.ctx.setStrokeStyle(this.color); // 设置线条颜色
					this.ctx.setLineWidth(this.lineWidth); // 设置线条宽度  
					this.ctx.rect(pointLT.X, pointLT.Y, width, height);
					this.ctx.stroke(); // 只绘制边框  
					this.ctx.draw(false);
				}
				// 如果你还想填充方形，可以调用 this.ctx.fill();  
			},
			//横线
			drawLine(x, y, isImg) {
				if (isImg) {
					this.myCanvasImg.beginPath();
					this.myCanvasImg.setStrokeStyle(this.color); // 设置线条颜色
					this.myCanvasImg.setLineWidth(this.lineWidth); // 设置线条宽度  
					this.myCanvasImg.moveTo(this.startX, this.startY);
					this.myCanvasImg.lineTo(x, y);
					this.myCanvasImg.stroke();
					this.myCanvasImg.draw(true);
				} else {
					this.ctx.beginPath();
					this.ctx.setStrokeStyle(this.color); // 设置线条颜色
					this.ctx.setLineWidth(this.lineWidth); // 设置线条宽度  
					this.ctx.moveTo(this.startX, this.startY);
					this.ctx.lineTo(x, y);
					this.ctx.stroke();
					this.ctx.draw(false);
				}
			},
			//正常线
			drawCurve(x, y) {
				this.ctx.beginPath();
				this.ctx.setStrokeStyle(this.color); // 设置线条颜色
				this.ctx.setLineWidth(this.lineWidth); // 设置线条宽度  
				// 把路径移动到画布中的指定点，不创建线条
				this.ctx.moveTo(this.startX, this.startY)
				// 增加一个新点，然后创建一条从上次指定点到目标点的线。
				this.ctx.lineTo(x, y);
				// 画出当前路径的边框。
				this.ctx.stroke();
				this.ctx.beginPath();
				this.myCanvasImg.beginPath();
				this.myCanvasImg.setStrokeStyle(this.color); // 设置线条颜色
				this.myCanvasImg.setLineWidth(this.lineWidth); // 设置线条宽度  
				this.myCanvasImg.moveTo(this.startX, this.startY)
				// 增加一个新点，然后创建一条从上次指定点到目标点的线。
				this.myCanvasImg.lineTo(x, y);
				// 画出当前路径的边框。
				this.myCanvasImg.stroke();
				this.myCanvasImg.draw(true);
				//将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。 
				// 本次绘制是否接着上一次绘制，即reserve参数为false，则在本次调用drawCanvas绘制之前native层应先清空画布再继续绘制；若reserver参数为true，则保留当前画布上的内容，本次调用drawCanvas绘制的内容覆盖在上面，默认 false
				this.ctx.draw(true);
				this.startX = x;
				this.startY = y;
			},
			Init() {
				console.log(this.picture, 0, 0, this.canvasStyle.w, this.canvasStyle.h);

				this.myCanvasImg = uni.createCanvasContext("myCanvasImg", this);
				//让线条圆润设置线条的端点样式。
				this.myCanvasImg.setLineCap('round');
				// 设置边框颜色。如果没有设置 fillStyle，默认颜色为 black。
				this.myCanvasImg.drawImage(this.picture, 0, 0, this.canvasStyle.w, this.canvasStyle.h);
				this.myCanvasImg.setStrokeStyle(this.color); // 设置线条颜色
				this.myCanvasImg.setLineWidth(this.lineWidth); // 设置线条宽度  
				// 设置填充色，如果没有设置 fillStyle，默认颜色为 black
				this.myCanvasImg.setFillStyle(this.color);
				this.myCanvasImg.draw();

				this.ctx = uni.createCanvasContext("myCanvas", this);
				// 让线条圆润 设置线条的端点样式。
				this.ctx.setLineCap('round');
				// 设置边框颜色。如果没有设置 fillStyle，默认颜色为 black。


				this.ctx.setStrokeStyle(this.color); // 设置线条颜色
				this.ctx.setLineWidth(this.lineWidth); // 设置线条宽度  
				// 设置填充色，如果没有设置 fillStyle，默认颜色为 black
				this.ctx.setFillStyle(this.color);
				// 设置线条的宽度。
				this.ctx.setLineWidth(5);
				// 绘制图片
				// this.ctx.drawImage(this.picture, 0, 0, this.canvasStyle.w, this.canvasStyle.h);
				// console.log(2);
				// // 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
				// this.ctx.draw();

				this.imageData = [this.picture]
			},
			/**
			 * 开始接触事件
			 * @param {Object} e
			 */
			penStart(e) {

				if (e.touches.length === 1) {
					this.isDrawing = true;
					let x = e.touches[0].x;
					let y = e.touches[0].y;
					this.startX = x;
					this.startY = y;
				}
			},
			/**
			 * 滑动事件
			 * @param {Object} e
			 */
			penMove(e) {
				console.log('滑动', e);
				if (this.isDrawing && e.touches.length === 1) {
					let x = e.touches[0].x;
					let y = e.touches[0].y;

					if (this.shape === 'line') {
						this.drawLine(x, y)
					} else if (this.shape === 'hollow-rect') {
						this.drawRect(x, y)
					} else if (this.shape === 'hollow-circle') {
						this.drawCircle(x, y)
					} else {
						this.drawCurve(x, y)

					}
				}



			},
			/**
			 * 离开屏幕事件
			 * @param {Object} e
			 */
			async penEnd(e) {
				console.log(e);
				if (this.isDrawing) {

					let x = e.changedTouches[0].x;
					let y = e.changedTouches[0].y;
					// this.ctx.draw(true);
					// this.myCanvasImg.draw(true);
					if (this.shape === 'line') {
						this.drawLine(x, y, true)
					} else if (this.shape === 'hollow-rect') {
						this.drawRect(x, y, true)
					} else if (this.shape === 'hollow-circle') {
						this.drawCircle(x, y, true)
					} else {

					}

					// this.drawCircle(x, y, true)
					this.saveImageData();
				}

			},
			saveImageData() {
				uni.showLoading({
					title: '标记保存中',
					mask: true,
				})
				uni.canvasToTempFilePath({
					canvasId: "myCanvasImg",
					quality: 0.5,
					success: (res) => {
						console.log(res.tempFilePath);
						console.log(this.imageData.length, 'this.imageData.length');
						console.log(this.curStep, 'this.curStep');
						console.log(this.imageData, 'this.imageData');
						if (this.imageData.length - 1 === this.curStep) {
							this.imageData.push(res.tempFilePath)
							this.curStep++
						} else {
							this.imageData = this.imageData.slice(0, this.curStep + 1)
							console.log(this.imageData, 'this.imageData');
							this.imageData.push(res.tempFilePath)
							this.curStep++
						}
						this.isDrawing = false;
						uni.hideLoading()
					},
					fail: err => {
						uni.hideLoading()
						console.log('saveImageData failed: ', err);
					}
				}, this);
			}

		},

	}
</script>

<style lang="scss" scoped>
	/*颜色区块横向滚动操作*/
	.lxy-content {
		// width: 100%;
		// height: 100rpx;
		box-sizing: border-box;

		// position: fixed;
		// top: 445rpx;
		.content-scroll {
			height: 100rpx;
			white-space: nowrap;

			.scroll-item {
				width: 64rpx;
				height: 64rpx;
				line-height: 62rpx;
				background: #FFFFFF;
				border-radius: 10rpx;
				display: inline-block;
				text-align: center;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 400;
				color: #666666;
				margin-left: 28rpx;
				padding: 0 24rpx;


			}

			.scroll-item:last-child {
				margin-right: 28rpx;
			}




		}
	}

	.active {
		border: 3px solid #ccc;
	}

	.activeSize {
		background-color: red;
	}
</style>